﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace OnTheWay.Controls
{
    public class TextBoxASCII : TextBox
    {
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);
            //this.IsInputMethodEnabled = false;
            //this.PreviewKeyDown += OnEventPreviewKeyDown;
            //this.PreviewTextInput += OnEventPreviewTextInput;
            AddHandler(DataObject.PastingEvent, new DataObjectPastingEventHandler(OnEventPasting));
            AddHandler(PreviewKeyDownEvent, new KeyEventHandler(OnEventPreviewKeyDown), true);
            AddHandler(PreviewTextInputEvent, new TextCompositionEventHandler(OnEventPreviewTextInput), true);
        }

        private void OnEventPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
                e.Handled = true;
        }

        private void OnEventPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!IsASCII(e.Text))
            {
                e.Handled = true;
            }
        }

        //检测粘贴
        private void OnEventPasting(object sender, DataObjectPastingEventArgs e)
        {
            if (e.DataObject.GetDataPresent(typeof(String)))
            {
                String text = (String)e.DataObject.GetData(typeof(String));
                if (!IsASCII(text))
                { e.CancelCommand(); }
            }
            else { e.CancelCommand(); } 
        }

        //isDigit是否是数字
        public static bool IsASCII(string _string)
        {
            if (string.IsNullOrEmpty(_string))
                return false;
            foreach (char c in _string)
            {
                if (c > 256 || c < 0)
                    //if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0，然后这种方法效率会搞10毫秒左右
                    return false;
            }
            return true;
        }

 
    }
}
